<!--
 * @Description: 大前端学习
 * @Version: H5
 * @Author: Ajax
 * @Date: 2020-04-22 21:58:45
 * @LastEditors: Ajax
 * @LastEditTime: 2020-04-23 12:08:55
 -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>校验码</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    div.content {
      width: 12.5rem;
      height: 6.25rem;
      line-height: 6.25rem;
      font-size: 2.5rem;
      color: #f00;
      text-align: center;
      border: 1px solid #ccc;
    }
  </style>
</head>

<body>

  <div class="content">1</div>
  <input type="text" name="check" id="check"> <button class="btn">验证</button>
</body>
<script>
  // 需求 : 随机码  math 内置对象 封装
  window.onload = function () {
    var code;
    var codeDiv = document.querySelector('.content');
    var checkObj = document.querySelector('#check');
    // console.log(checkObj);
    var checkBtn = document.querySelector('.btn');
    // 随机数
    createCode();
    function random(max, min) {
      return Math.floor(Math.random() * (max - min) + min);
    }
    function createCode() {
      code = '';
      var codeLength = 4;
      var randomCode = ['65'];
      var arr = [];
      var newArr = [];
      // 小型工厂 回调函数
      function forEach(callback, begin, end) {
        var i = begin || 0;
        for (i; i < end; i++) {
          callback(i);
        }
      }
      forEach(function (i) {
        arr[i] = (String.fromCharCode((97 + i)));
      }, 0, 26)
      forEach(function (i) {
        newArr[i] = i;
      }, 0, 10)
      forEach(function (i) {
        arr.push(newArr[i]);
      }, 0, newArr.length)
      forEach(function (i) {
        var index = random(0, 36);
        code += arr[index];
      }, 0, codeLength)
      codeDiv.innerHTML = code;
    }
    // 验证

    checkBtn.addEventListener('click', function () {
      var newCode = checkObj.value.toLowerCase();
      if (newCode == code) {
        alert('验证码正确')
        window.location.href = 'https://www.baidu.com';
      } else {
        alert('验证码错误');
        createCode();
      }
    })
  }


</script>

</html>